package com.duoduo.demo.springnoxml.websocket;

import java.io.IOException;
import java.io.InputStream;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * 控制台日志处理器
 * @url http://blog.csdn.net/xiao__gui/article/details/50041673
 * @author chengesheng@kedacom.com
 * @date 2017年12月7日上午10:57:47
 */
@ServerEndpoint("/console")
public class ConsoleWebsocketHandler {

	private Session session;
	private Process process;
	private InputStream inputStream;

	/**
	 * 新的WebSocket请求开启
	 */
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;

		try {
			session.getBasicRemote().sendText("已连接到服务器<br>");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * WebSocket请求关闭
	 */
	@OnClose
	public void onClose() {
		try {
			session.getBasicRemote().sendText("断开连接<br>");
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			if (inputStream != null) {
				inputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
	}

	@OnError
	public void onError(Throwable thr) {
		thr.printStackTrace();
	}

	/**
	 * 执行命令
	 * @param command 执行的命令，如："tail -f /var/log/syslog"
	 */
	public void executeCommand(String command) {
		try {
			// 执行tail -f命令
			process = Runtime.getRuntime().exec(command);
			inputStream = process.getInputStream();

			// 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
			ConsoleWebsocketThread thread = new ConsoleWebsocketThread(inputStream, session);
			thread.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
